//
//  YTLoginViewModel.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/4/28.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTLoginViewModel.h"
#import "YTUserLoginAPI.h"
#import <XGPush/XGPush.h>
#import <JPush/JPUSHService.h>

@interface YTLoginViewModel ()
@property (nonatomic, strong, readwrite) RACSignal *phoneVerify;
@property (nonatomic, strong, readwrite) RACSignal *passwordVerify;
@property (nonatomic, strong, readwrite) RACSignal *verifyAll;
@property (nonatomic, strong, readwrite) RACCommand *loginCommand;
@end

@implementation YTLoginViewModel

- (instancetype)init
{
    self = [super init];
    if (self) {
        _phoneVerify = [RACObserve(self, phoneNum) map:^id(NSString *phone) {
            if ([[self.areaCode substringFromIndex:2] isEqualToString:@"86"]) {
                return @([NSString yt_checkTelNumberValidate:phone]);
            }
            return @((BOOL)(phone.length >= 5));
        }];
        
        _passwordVerify = [RACObserve(self, password) map:[NSObject yt_validateStrWithLenght:6]];
        
        RACSignal *checkProtocolVerify = [RACObserve(self, isChecked) map:^id(NSNumber *state) {
            return state;
        }];
        
        _verifyAll = [RACSignal combineLatest:@[_phoneVerify, _passwordVerify, checkProtocolVerify]
                                       reduce:^id (NSNumber *phonePass, NSNumber *passwordPass, NSNumber *state){
            return @([phonePass boolValue] && [passwordPass boolValue] && [state boolValue]);
        }];
        
        @weakify(self);
        _loginCommand = [[RACCommand alloc] initWithEnabled:_verifyAll signalBlock:^RACSignal *(id input) {
            @strongify(self);
            RACSignal *loginSignal = [YTUserLoginAPI userLogin:self.phoneNum
                                                      password:self.password
                                                      areaCode:[self.areaCode substringFromIndex:2]];
            [loginSignal subscribeNext:^(NSDictionary *response) {
                if ([response[@"resultCode"] integerValue] == 1000) {
                    NSDictionary *userInfo = response[@"responseData"];
                    [self cacheUserInfo:userInfo];
                    [self bindingXGPush:userInfo[@"userId"]];
                }
            }];
            return loginSignal;
        }];
    }
    return self;
}

- (void)cacheUserInfo:(NSDictionary *)userInfo {
    [[NSUserDefaults standardUserDefaults] setObject:userInfo[@"userId"] forKey:kUserIdDefaults];
    [[NSUserDefaults standardUserDefaults] setObject:userInfo[@"rongCloudToken"] forKey:kRongYunToken];
    [[NSUserDefaults standardUserDefaults] setObject:userInfo[@"token"] forKey:kUserToken];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:YTUserLoginSuccessNotification object:userInfo[@"userId"]];
    
    // 绑定极光推送
    NSSet *set = [NSSet setWithObject:@"tag_1"];
    [JPUSHService setTags:set alias:userInfo[@"userId"] fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        NSLog(@"**********************分割线**********************");
        NSLog(@"%zd", iResCode);
        NSLog(@"%@", iTags);
        NSLog(@"%@", iAlias);
    }];
}

- (void)bindingXGPush:(NSString *)userID {
    void (^successBlock)(void) = ^(void){
        NSLog(@"[XGPush]handleLaunching's successBlock");
    };
    
    NSData *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:kDeviceToken];
    if (deviceToken) {
        [XGPush registerDevice:deviceToken];
    }
    
    [XGPush initForReregister:successBlock];
    [XGPush setAccount:userID];
}

@end
